package com.lovo.service.impl;

import com.lovo.dao.CourseBeanDAO;
import com.lovo.model.CourseBean;
import com.lovo.model.DTO.CourseDTO;
import com.lovo.model.vo.PageVO;
import com.lovo.service.CourseService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CourseImpl implements CourseService {
    @Resource
    private CourseBeanDAO courseBeanDAO;

    @Override
    public PageVO findAll(Integer page, Integer size) {
        Page<CourseBean> pageObj = courseBeanDAO.findAll(PageRequest.of(page - 1, size));
        List<CourseDTO> courseDTOList = new ArrayList();
        for (CourseBean c : pageObj.getContent()) {
            CourseDTO courseDTO = new CourseDTO(c.getCourseId(), c.getName());
            courseDTOList.add(courseDTO);
        }
        return new PageVO(pageObj.getNumber() + 1, pageObj.getSize(), pageObj.getTotalElements(), courseDTOList);
    }

    @Override
    public CourseDTO findById(Integer CourseId) {
        CourseBean courseBean = courseBeanDAO.findByCourseId(CourseId);
        CourseDTO courseDTO = new CourseDTO(courseBean.getCourseId(), courseBean.getName());
        return courseDTO;
    }

    @Override
    public void add(CourseDTO courseDTO) {
        CourseBean courseBean = new CourseBean(courseDTO.getName());
        courseBeanDAO.save(courseBean);
    }

    @Override
    public void update(Integer id, CourseDTO courseDTO) {
        CourseBean courseBean = new CourseBean(courseDTO.getName());
        courseBean.setCourseId(id);
        courseBeanDAO.save(courseBean);
    }

    @Override
    public void del(Integer id) {
        CourseBean courseBean = new CourseBean();
        courseBean.setCourseId(id);
        courseBeanDAO.delete(courseBean);
    }

}
